/*
 * Copyright (C) 2014 Lucid Wolf
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.lucidhex.equation.parser.expr;

import com.lucidhex.equation.parser.Expr;

/**
 *  
 * @author Lucid Wolf
 */
public class BinaryExpr extends Expr {
    int rator;
    Expr rand0, rand1;

    public BinaryExpr(int rator, Expr rand0, Expr rand1) {
	this.rator = rator;
	this.rand0 = rand0;
	this.rand1 = rand1;
    }
    @Override
    public double value() {
	double arg0 = rand0.value();
	double arg1 = rand1.value();
	switch (rator) {
	case ADD:   return arg0 + arg1;
	case SUB:   return arg0 - arg1;
	case MUL:   return arg0 * arg1;
	case DIV:   return arg0 / arg1; // division by 0 has IEEE 754 behavior
	case POW:   return Math.pow(arg0, arg1);
	case ATAN2: return Math.atan2(arg0, arg1);
	case MAX:   return arg0 < arg1 ? arg1 : arg0;
	case MIN:   return arg0 < arg1 ? arg0 : arg1;
        case LT:    return arg0 <  arg1 ? 1.0 : 0.0;
        case LE:    return arg0 <= arg1 ? 1.0 : 0.0;
        case EQ:    return arg0 == arg1 ? 1.0 : 0.0;
        case NE:    return arg0 != arg1 ? 1.0 : 0.0;
        case GE:    return arg0 >= arg1 ? 1.0 : 0.0;
        case GT:    return arg0  > arg1 ? 1.0 : 0.0;
        case AND:   return arg0 != 0 && arg1 != 0 ? 1.0 : 0.0;
        case OR:    return arg0 != 0 || arg1 != 0 ? 1.0 : 0.0; 
	default: throw new RuntimeException("BUG: bad rator");
	}
    }
}
